package nextgen
import grails.converters.XML
import grails.converters.JSON

class RestController {
	def computeFactsService
	def renderFactsService
	
	def list= {
		render nextgen.Interoperability.list() as XML
	}
	
	def listJson= {
		render nextgen.Interoperability.list() as JSON
	}
	
	def produceRdfJson= {
		def interop= new File('web-app/resources/interoperability.json').text
		render interop	
	}
	
	def produceRdfNt= {
		render new File('web-app/resources/interoperability.nt').text
	}
	
	def insert= {
		def interoperability= new nextgen.Interoperability(params['interoperability'])
		interoperability.toUrl= params.interoperability.toUrl
		interoperability.fromUrl= params.interoperability.fromUrl
		interoperability.save()
		if (!interoperability.hasErrors()) { render interoperability as XML }
		else { render interoperability.errors as XML}
	}
	
	def deleteFrom= {
		def interops= Interoperability.findAllByFromUrl(params.url)
		if (interops != []) {
			interops.each { fact ->
				fact.delete()
			}
			response.status= 204
		}
		else { SentNotFoundResponse() }
	}
	
	def deleteTo= {
		def interops= Interoperability.findAllByToUrl(params.url)
		if (interops != []) {
			interops.each { fact ->
				fact.delete()
			}
			response.status= 204
		}
		else { SentNotFoundResponse() }
	}
	
	def showFrom= {
		def urls= Interoperability.findAllByFromUrl(params.url)
		if (urls == []) { response.status= 404 }
		else { render urls as XML } 
	}
	
	def showTo= {
		def urls= Interoperability.findAllByToUrl(params.url)
		if (urls == []) { response.status= 404 }
		else { render urls as XML } 
	}
	
	def updateFacts= {
		computeFactsService.computeFacts()
		render 'ok'
		renderFactsService.buildRdfNt()
		renderFactsService.buildRdfJson()
	}
}
